package com.example.config;

import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @BelongsProject: yst-lube -addDoorls
 * @BelongsPackage: com.yunsitu.entity.drools
 * @Author: dyz
 * @CreateTime: 16:15
 * @Version: 1.0
 */
public class KieSessionUtils {
    private KieSessionUtils() {

    }

    //xls 文件解析为String
    public static String getDRl(String realPath) throws FileNotFoundException {
        File file = new File(realPath);
        FileInputStream fileInputStream = new FileInputStream(realPath);
        SpreadsheetCompiler spreadsheetCompiler = new SpreadsheetCompiler();
        String compile = spreadsheetCompiler.compile(fileInputStream, InputType.XLS);
  //  System.out.println(compile);
        return compile;
    }

    //drl 为含有内容的字符串
    public static KieSession createKieSessionFromDrl(String drl) {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        //校验
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) {
            List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
            for (Message message : messages) {
                System.out.println("Error:" + message.getText());
            }
        }

        KieSession kieSession = kieHelper.build().newKieSession();
        return kieSession;
    }

    //realpath 为Excel 文件绝对路径
    public static KieSession getKieSessionFromXLS(String realpath) throws FileNotFoundException {
        return createKieSessionFromDrl(getDRl(realpath));
    }


}
